package com.wocai.jrt.orgadmin.ads.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.ads.model.Ads;
import com.wocai.jrt.orgadmin.ads.model.AdsBean;
import com.wocai.jrt.orgadmin.ads.service.spi.AdsService;
import com.wocai.jrt.orgadmin.news.bean.BasicBean;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.ImgType;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 广告控制器
 * 
 * @author yinlei
 * @date 2015-8-15 14:11:47
 */
@Controller
@RequestMapping("/noads")
public class AdsAction extends GenericAction<Ads> {
	private static final Logger LOGGER = LoggerFactory.getLogger(AdsAction.class);

	@Inject
	private AdsService adsServiceImpl;
	@Inject
	private ProductService productServiceImpl;

	/**
	 * 获得广告List，Json格式。
	 * 
	 * @param model
	 *            参数
	 * @return 广告List
	 */
	@RequestMapping("/list")
	public String list(Ads model, Map<String, Object> maps) {
		try {
			List<Ads> list = adsServiceImpl.pagedList(model);
			maps.put("list", list);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "noads/list";
	}

	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody BasicBean bean) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			AdsBean adsBean = new AdsBean();
			adsBean.setOrderBy("orders desc");

			AdsBean.Criteria criteria = adsBean.createCriteria();
			if (null != bean.getTitle()) {
				// criteria.andAdsNameLike(bean.getTitle());
				criteria.andAdsNameLike("%" + bean.getTitle() + "%");
			}
			if (null != bean.getBeginDate()) {
				criteria.andPublishTimeGreaterThanOrEqualTo(bean.getBeginDate());
			}
			if (null != bean.getEndDate()) {
				bean.setEndDate(new DateTime(bean.getEndDate()).plusDays(1).toDate());
				criteria.andPublishTimeLessThan(bean.getEndDate());
			}
			if (0 != bean.getPageSize()) {
				adsBean.setStart(bean.getStart());
				adsBean.setPageSize(bean.getPageSize());
			}
			int i = bean.getStatus();
			if (i != -1) {
				if (i == 1) {
					criteria.andStateEqualTo(true);
				} else if (i == 0) {
					criteria.andStateEqualTo(false);
				}
			}
			int j = bean.getPlatform();
			if (j != 0) {
				criteria.andPlatformEqualTo(j);
			}
			criteria.andOrgIdEqualTo(UserUtils.getOrgId());

			Product product = new Product();
			product.setOrgId(UserUtils.getOrgId());
			List<Product> productList = productServiceImpl.pagedList(product);
			List<Ads> list = adsServiceImpl.pagedForList(adsBean);

			for (Ads ads : list) {
				for (Product product2 : productList) {
					if (product2.getId().equals(ads.getProductId())) {
						ads.setProductName(product2.getProductName());
					}
				}
			}

			// 统计的时候，不需要分页
			adsBean.setStart(null);
			long totalRecord = adsServiceImpl.count(adsBean);

			// jQuery datatable 就是这样的参数，阿西吧
			// result.put("sEcho", user.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("news query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 根据Id获得广告实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 广告实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public Ads get(String id) {
		Ads model = null;
		try {
			model = adsServiceImpl.get(id);
		} catch (Exception e) {
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
		return model;
	}

	/**
	 * 跳转到新增页面
	 * 
	 * @return 新增页面逻辑视图
	 */
	@RequestMapping("/add")
	public String add(Map<String, Object> maps) {
		try {
			Product product = new Product();
			product.setOrgId(UserUtils.getOrgId());
			List<Product> list = productServiceImpl.queryList(product);
			//List<Product> list = productServiceImpl.pagedList(product);
			maps.put("productList", list);

			Ads ads = new Ads();
			ads.setOrderBy("orders desc");
			ads.setOrgId(UserUtils.getOrgId());
			List<Ads> adsList = adsServiceImpl.pagedList(ads);
			int orders = 0;
			if (adsList != null && adsList.size() > 0) {
				orders = adsList.get(0).getOrders() + 1;
			}
			maps.put("orders", orders);

		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "noads/add";
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(@RequestBody Ads model) {
		JsonBean bean = new JsonBean();
		try {
			model.setId(ObjectId.get().toString());
			model.setOrgId(UserUtils.getOrgId());
			if (model.getState()) {
				model.setPublishTime(new Date());
				Ads paramT = new Ads();
				paramT.setOrgId(UserUtils.getOrgId());
				paramT.setPlatform(model.getPlatform());
				paramT.setState(true);
				List<Ads> adsList = adsServiceImpl.queryList(paramT);
				if (adsList != null) {
					if (adsList.size() >= 5) {
						bean.setMessage("同一个平台已发布的广告不能超过5个");
						bean.setCode(0);
						return bean;
					}
				}
			}
			if (null != model.getUrl()) {
				model.setProductId("");
			}
			int result = adsServiceImpl.save(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("save record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 查看广告详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 广告详情页
	 */
	@RequestMapping("/detail")
	public String detail(Ads model, Map<String, Object> maps) {
		try {
			model = adsServiceImpl.get(model.getId());
			maps.put("model", model);// 将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "noads/detail";
	}

	/**
	 * 跳转到编辑信息页面
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 编辑页面
	 */
	@RequestMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			Ads model = new Ads();
			model = adsServiceImpl.get(id);
			maps.put("model", model);
			Product product = new Product();
			product.setOrgId(UserUtils.getOrgId());
			List<Product> list = productServiceImpl.pagedList(product);
			maps.put("productList", list);
		} catch (Exception e) {
			LOGGER.error("edit record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "noads/edit";
	}

	/**
	 * 更新广告信息
	 * 
	 * @param model
	 *            要更新的广告信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(@RequestBody Ads model) {
		JsonBean bean = new JsonBean();
		try {
			if (model.getState()) {
				model.setPublishTime(new Date());
				Ads paramT = new Ads();
				paramT.setOrgId(UserUtils.getOrgId());
				paramT.setPlatform(model.getPlatform());
				paramT.setState(true);
				List<Ads> adsList = adsServiceImpl.queryList(paramT);
				if (adsList != null) {
					if (adsList.size() >= 5) {
						bean.setMessage("已发布的广告不能超过5个");
						bean.setCode(0);
						return bean;
					}
				}
			}
			//url不为空，productId必须为空
			if (!StringUtils.isAnyBlank(model.getUrl())) {
				model.setProductId("");
			}else if (!StringUtils.isAnyBlank(model.getProductId())) {
				//productId不为空，url必须为空
				model.setUrl("");
			}else {
				model.setProductId("");
				model.setUrl("");
			}
			
			int result = adsServiceImpl.updateById(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 删除广告信息
	 * 
	 * @param id
	 *            要删除的广告ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String id) {
		JsonBean bean = new JsonBean();
		try {
			Ads ads = adsServiceImpl.get(id);
			if (ads == null) {
				bean.setCode(0);
				bean.setMessage("该新闻不存在");
				return bean;
			}

			int i = ads.getThumbnail().indexOf("ads/default/default");
			if (i == -1) {
				File file = new File(ads.getThumbnail());
				MyFileUtils.deleteFileDir(file);
			}

			int result = adsServiceImpl.deleteById(id);

			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete record success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}
	
	@ResponseBody
	@RequestMapping("/uploadFile")
	public JsonBean uploadFile(MultipartFile file, HttpServletResponse response) {
		JsonBean json = new JsonBean();
		if (file.isEmpty()) {
			json.setCode(0);
			json.setMessage("上传的文件不存在");
		}
		try {
			json.setCode(1);
			// json.setData(MyFileUtils.uploadFile(file, fileType));
			json.setData(MyFileUtils.uploadImg(file, ImgType.ADS));
		} catch (IOException e) {
			json.setCode(0);
			json.setMessage("上传文件出错");
			LOGGER.error("upload file error, errorMsg=[{}].", e.getMessage());
		}
		// response.setContentType("text/x-json");
		// OutputStream os = response.getOutputStream();
		// // 将验证码写入输出流
		// os.write();
		// os.flush();
		return json;
	}
}
